'use client';

import { useEffect, useState } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import Image from 'next/image';
import MobileLayout from '../../../components/layout/MobileLayout';
import { useSocket, User, FriendRequest } from '../../../context/SocketContext';
import styles from './page.module.css';

export default function FriendPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const userId = searchParams.get('id');
  const mode = searchParams.get('mode') || 'view'; // view, add, verify
  
  const {
    currentUser,
    friends,
    friendRequests,
    sendFriendRequest,
    acceptFriendRequest,
    rejectFriendRequest,
    removeFriend
  } = useSocket();
  
  const [user, setUser] = useState<User | null>(null);
  const [friendRequest, setFriendRequest] = useState<FriendRequest | null>(null);
  const [requestMessage, setRequestMessage] = useState('');
  
  // 获取用户信息
  useEffect(() => {
    if (userId && mode === 'view') {
      const foundFriend = friends.find(friend => friend.id === userId);
      if (foundFriend) {
        setUser(foundFriend);
      }
    } else if (userId && mode === 'verify') {
      const foundRequest = friendRequests.find(request => 
        request.id === userId || request.sender === userId || request.receiver === userId
      );
      if (foundRequest) {
        setFriendRequest(foundRequest);
        // 找到发送请求的用户
        const requestUser = friends.find(friend => friend.id === foundRequest.sender) || 
                           { id: foundRequest.sender, username: '用户', avatar: '/avatars/avatar1.svg' };
        setUser(requestUser);
      }
    }
  }, [userId, mode, friends, friendRequests]);
  
  // 处理返回
  const handleBack = () => {
    router.push('/message');
  };
  
  // 处理发送好友请求
  const handleSendRequest = () => {
    if (userId && requestMessage.trim()) {
      sendFriendRequest(userId, requestMessage);
      router.push('/message');
    }
  };
  
  // 处理接受好友请求
  const handleAcceptRequest = () => {
    if (friendRequest) {
      acceptFriendRequest(friendRequest.id);
      router.push('/message');
    }
  };
  
  // 处理拒绝好友请求
  const handleRejectRequest = () => {
    if (friendRequest) {
      rejectFriendRequest(friendRequest.id);
      router.push('/message');
    }
  };
  
  // 处理删除好友
  const handleRemoveFriend = () => {
    if (userId) {
      removeFriend(userId);
      router.push('/message');
    }
  };
  
  // 处理开始聊天
  const handleStartChat = () => {
    if (user) {
      router.push(`/message/chat?id=${user.id}&type=private&name=${user.username}&avatar=${encodeURIComponent(user.avatar)}`);
    }
  };
  
  if (!userId) {
    return <div>无效的用户ID</div>;
  }
  
  return (
    <MobileLayout>
      <div className={styles.friendPage}>
        {/* 头部 */}
        <div className={styles.header}>
          <div className={styles.backButton} onClick={handleBack}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M20 11H7.83L13.42 5.41L12 4L4 12L12 20L13.41 18.59L7.83 13H20V11Z" fill="#333"/>
            </svg>
          </div>
          <div className={styles.headerTitle}>
            {mode === 'view' ? '好友信息' : mode === 'add' ? '添加好友' : '好友验证'}
          </div>
        </div>
        
        {/* 用户信息 */}
        <div className={styles.userInfo}>
          <div className={styles.userAvatar}>
            <Image 
              src={user?.avatar || '/avatars/avatar1.svg'} 
              alt={user?.username || '用户'} 
              width={80} 
              height={80} 
              className={styles.avatarLarge}
            />
          </div>
          <div className={styles.userName}>
            {user?.username || '用户'}
          </div>
          {user?.id && (
            <div className={styles.userId}>
              ID: {user.id.substring(0, 8)}
            </div>
          )}
        </div>
        
        {/* 查看模式 - 好友操作 */}
        {mode === 'view' && (
          <div className={styles.actionButtons}>
            <button className={styles.primaryButton} onClick={handleStartChat}>
              发送消息
            </button>
            <button className={styles.dangerButton} onClick={handleRemoveFriend}>
              删除好友
            </button>
          </div>
        )}
        
        {/* 添加模式 - 发送请求 */}
        {mode === 'add' && (
          <div className={styles.addFriendForm}>
            <div className={styles.formGroup}>
              <label className={styles.formLabel}>验证消息</label>
              <textarea 
                className={styles.formTextarea}
                placeholder="请输入验证消息..."
                value={requestMessage}
                onChange={(e) => setRequestMessage(e.target.value)}
              />
            </div>
            <button 
              className={`${styles.primaryButton} ${!requestMessage.trim() ? styles.disabledButton : ''}`}
              onClick={handleSendRequest}
              disabled={!requestMessage.trim()}
            >
              发送请求
            </button>
          </div>
        )}
        
        {/* 验证模式 - 处理请求 */}
        {mode === 'verify' && friendRequest && (
          <div className={styles.verifyRequest}>
            <div className={styles.requestMessage}>
              <div className={styles.requestLabel}>验证消息:</div>
              <div className={styles.requestContent}>{friendRequest.message}</div>
            </div>
            <div className={styles.actionButtons}>
              <button className={styles.primaryButton} onClick={handleAcceptRequest}>
                接受请求
              </button>
              <button className={styles.secondaryButton} onClick={handleRejectRequest}>
                拒绝请求
              </button>
            </div>
          </div>
        )}
      </div>
    </MobileLayout>
  );
}